<?php

namespace app\admin\controller\behavior;

use app\admin\model\DormitoryDorm;
use app\admin\model\Student;
use app\common\controller\Backend;
use app\common\model\BehaviorRecord;
use app\common\model\BehaviorRecordDetail;
use think\Db;

class Record extends Backend
{
    /**
     * @var \app\common\model\BehaviorRecordDetail
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = [];
    protected $excludeFields = [''];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('BehaviorRecordDetail');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('a')
                ->join('__BEHAVIOR_RECORD__ b', 'b.id = a.record_id', 'left')
                ->join('__STUDENT__ c', 'c.id = b.student_id', 'left')
                ->join('__DORMITORY_GARDEN__ e', 'e.number = b.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = b.building_number and d.garden_number = b.garden_number', 'left')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('a')
                ->join('__BEHAVIOR_RECORD__ b', 'b.id = a.record_id', 'left')
                ->join('__STUDENT__ c', 'c.id = b.student_id', 'left')
                ->join('__DORMITORY_GARDEN__ e', 'e.number = b.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = b.building_number and d.garden_number = b.garden_number', 'left')
                ->where($where)
                ->field('a.id,b.record_user_group,b.dorm_number,e.name garden_name,d.name building_name,b.created_at,b.student_id,a.behavior_name,a.score,c.name student_name,c.gender student_gender,c.number student_number')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $key => $value) {
                if (isset(Student::$genderList[$value['student_gender']])) {
                    $list[$key]['student_gender_text'] = Student::$genderList[$value['student_gender']];
                } else {
                    $list[$key]['student_gender_text'] = '';
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $ids = explode(',', $ids);
            $ids = array_unique($ids);

            $record_detail_list = $this->model->where('id', 'in', $ids)->select();

            foreach ($record_detail_list as $key => $value) {

                Db::startTrans();
                try {

                    $record = BehaviorRecord::where('id', $value['record_id'])->find();

                    if (!$record) continue;

                    $dorm = DormitoryDorm::where('garden_number', $record['garden_number'])
                        ->where('building_number', $record['building_number'])
                        ->where('number', $record['dorm_number'])
                        ->find();

                    if (!$dorm) continue;

                    // 判断删除的事学生分 还是 寝室分
                    if ($record['student_id']) {

                        $result = BehaviorRecord::alias('a')
                            ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id')
                            ->where('a.garden_number', $record['garden_number'])
                            ->where('a.building_number', $record['building_number'])
                            ->where('a.dorm_number', $record['dorm_number'])
                            ->where('a.student_id', '>', 0)
                            ->where('a.id', $record['id'])
                            ->field('COUNT(DISTINCT(a.student_id)) student_count,SUM(b.score) student_score')
                            ->find();

                        $student_count = $result['student_count'] ? $result['student_count'] : 0;
                        $student_score = $result['student_score'] ? $result['student_score'] : 0;

                        $score = 0;
                        if ($student_count)
                            $score = (float)number_format(($student_score - $value['score']) / $student_count, 2, '.', '');

                        $dorm->total_score = $dorm['score'] + $score;
                        $dorm->save();

                        Student::where('id', $record['student_id'])->setDec('score', $value['score']);

                    } else {

                        $dorm->setDec('score', $value['score']);
                        $dorm->setDec('total_score', $value['score']);
                    }

                    $this->model->where('id', $value['id'])->delete();

                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    $this->error($e->getMessage() ? $e->getMessage() : '删除失败');
                }
            }


            $this->success();
        }

        $this->error();
    }

}
